/*
 * Copyright (C) 2010 Apple Inc. All rights reserved.
 * Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies)
 * Copyright (C) 2011 Igalia S.L.
 * Copyright (C) 2012 Sony Computer Entertainment Inc.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS''
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
 * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS
 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
 * THE POSSIBILITY OF SUCH DAMAGE.
 */

#include "config.h"
#include "Connection.h"

#include "ArgumentEncoder.h"
#include "BinarySemaphore.h"
#include <wtf/DoublyLinkedList.h>
#include <wtf/Functional.h>
#include <wtf/RandomNumber.h>
#include <wtf/text/WTFString.h>

using namespace std;

#if 0
#  include <stdio.h>
#  define CONNECTION_LOG(...) printf(__VA_ARGS__)
#else
#  define CONNECTION_LOG(...) ((void)0)
#endif

#define CONNECTION_BUFFER_SIZE 1024

namespace CoreIPC {

enum {
    MessageBodyIsOOL = 1U << 31
};

class MessageInfo {
public:
    MessageInfo() { }

    MessageInfo(MessageID messageID, size_t bodySize, size_t initialAttachmentCount)
        : m_messageID(messageID.toInt())
        , m_bodySize(bodySize)
        , m_attachmentCount(initialAttachmentCount)
    {
        ASSERT(!(m_messageID & MessageBodyIsOOL));
    }

    void setMessageBodyOOL()
    {
        ASSERT(!isMessageBodyOOL());

        m_messageID |= MessageBodyIsOOL;
        m_attachmentCount++;
    }

    bool isMessageBodyOOL() const { return m_messageID & MessageBodyIsOOL; }

    size_t bodySize() const { return m_bodySize; }

    MessageID messageID() const { return MessageID::fromInt(m_messageID & ~MessageBodyIsOOL); }

    size_t attachmentCount() const { return m_attachmentCount; }

private:
    uint32_t m_messageID;
    size_t m_bodySize;
    size_t m_attachmentCount;
};

void Connection::platformInitialize(Identifier identifier)
{
    m_handle = identifier;
    m_readBufferSize = 0;
    MutexLocker locker(m_writeBufferLock);
    m_writeBufferOffset = 0;
}

void Connection::platformInvalidate()
{
    Manx::Pipe::close(m_handle);
}

bool Connection::open()
{
    m_isConnected = true;
    m_connectionQueue.registerSocketEventHandler(m_handle, bind(&Connection::pollSocket, this));
    return true;
}

bool Connection::platformCanSendOutgoingMessages() const
{
    MutexLocker locker(m_writeBufferLock);
    return !m_writeBuffer.size();
}

bool Connection::processMessage()
{
    if (m_readBufferSize < sizeof(MessageInfo))
        return false;

    uint8_t* messageData = m_readBuffer.data();
    uint8_t* messageBody = messageData + sizeof(MessageInfo);
    MessageInfo* messageInfo = reinterpret_cast<MessageInfo*>(messageData);
    size_t messageLength = sizeof(MessageInfo) + messageInfo->bodySize();
    if (m_readBufferSize < messageLength)
        return false;

    ArgumentDecoder* argumentDecoder;
    argumentDecoder = new ArgumentDecoder(messageBody, messageInfo->bodySize());

    processIncomingMessage(messageInfo->messageID(), adoptPtr(argumentDecoder));

    if (m_readBufferSize > messageLength) {
        memmove(m_readBuffer.data(), m_readBuffer.data() + messageLength, m_readBufferSize - messageLength);
        m_readBufferSize -= messageLength;
    } else {
        m_readBuffer.resize(0);
        m_readBufferSize = 0;
    }

    return true;
}

void Connection::readyReadHandler()
{
    while (true) {
        m_readBuffer.resize(m_readBufferSize + CONNECTION_BUFFER_SIZE);
        size_t read = 0;
        bool ok = Manx::Pipe::read(m_handle, m_readBuffer.data() + m_readBufferSize, CONNECTION_BUFFER_SIZE, &read);
        if (ok)
            m_readBufferSize += read;
        while (processMessage()) { }
        if (!ok)
            break;
        if (read < CONNECTION_BUFFER_SIZE)
            break;
    }
}

void Connection::readyWriteHandler()
{
    bool willSend = false;
    {
        MutexLocker locker(m_writeBufferLock);
        if (!m_writeBuffer.size())
            return;
        size_t written = 0;
        bool ok = Manx::Pipe::write(m_handle, m_writeBuffer.data() + m_writeBufferOffset, m_writeBuffer.size() - m_writeBufferOffset, &written);
        if (ok && written > 0) {
            m_writeBufferOffset += written;
            ASSERT(m_writeBufferOffset <= m_writeBuffer.size());
            if (m_writeBuffer.size() == m_writeBufferOffset) {
                m_writeBufferOffset = 0;
                m_writeBuffer.resize(0);
                willSend = true;
            }
        }
    }
    if (willSend) {
        // Now that the pending write has finished, we can try to send a new message.
        sendOutgoingMessages();
    }
}

void Connection::pollSocket()
{
    readyReadHandler();
    readyWriteHandler();
}

bool Connection::sendOutgoingMessage(MessageID messageID, PassOwnPtr<ArgumentEncoder> arguments)
{
    MessageInfo messageInfo(messageID, arguments->bufferSize(), 0);
    size_t messageSizeWithBodyInline = sizeof(messageInfo) + arguments->bufferSize();

    {
        MutexLocker locker(m_writeBufferLock);
        m_writeBufferOffset = 0;
        m_writeBuffer.resize(messageSizeWithBodyInline);
        memcpy(m_writeBuffer.data(), &messageInfo, sizeof messageInfo);
        memcpy(m_writeBuffer.data() + sizeof messageInfo, arguments->buffer(), arguments->bufferSize());
    }

    readyWriteHandler();
    
    return false;
}

} // namespace CoreIPC
